﻿package com.imoblife.brainwavestus.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class UnzipFile {
	private static byte zipBuffer[];

	static {
		zipBuffer = new byte[1024];
	}

	public static boolean zipToFile(String sZipPathFile, String sDestPath) {
		boolean flag = false;
		try {
			FileInputStream fins = new FileInputStream(sZipPathFile);
			ZipInputStream zins = new ZipInputStream(fins);
			ZipEntry ze = null;

			while ((ze = zins.getNextEntry()) != null) {

				File zfile = new File(sDestPath + "//" + ze.getName());

				System.out.println("sDestPath + ze.getName()" + sDestPath
						+ "//" + ze.getName());
				File fpath = new File(zfile.getParentFile().getPath());

				System.out.println("zfile.getParentFile().getPath()"
						+ zfile.getParentFile().getPath());

				if (ze.isDirectory()) {
					if (!zfile.exists())
						zfile.mkdirs();
					zins.closeEntry();

				} else {
					if (!fpath.exists())
						fpath.mkdirs();
					
					FileOutputStream fouts = new FileOutputStream(zfile);
					int i;
					String zfilePath = zfile.getAbsolutePath();
					while ((i = zins.read(zipBuffer)) != -1) {
						fouts.write(zipBuffer, 0, i);
					}
					zins.closeEntry();
					fouts.close();

					if (zfilePath.endsWith(".zip")) {
						zipToFile(
								zfilePath,
								zfilePath.substring(0,
										zfilePath.lastIndexOf(".zip")));
					}

				}
			}
			fins.close();
			zins.close();

			// 如果需要解压完后删除ZIP文件可以
			File file = new File(sZipPathFile);
			// file.delete();
			flag = true;
		} catch (Exception e) {
			System.err.println("Extract error:" + e.getMessage());
		}
		return flag;
	}

	public static void main(String[] args) {
		String sZipPathFile = "C:/1.zip";
		String sDestPath = "C:/1";
		UnzipFile.zipToFile(sZipPathFile, sDestPath);
	}
}
